package main

import (
  "sdl"
  "sdl/ttf"
  "log"
  "fmt"
)

type ui struct {
  base   Window
  active Window
  font   *ttf.Font
}

var uiInstance *ui

func UIInit(base Window, font *ttf.Font) {

  fmt.Printf("UIInit: %p, %T\n", base, base)

  uiInstance = new(ui)
  uiInstance.base = base
  uiInstance.active = base
  uiInstance.font = font

}

func GetFont() *ttf.Font {
  return uiInstance.font
}

func GetBaseWindow() Window {
  return uiInstance.base
}

func GetActiveWindow() Window {
  return uiInstance.active
}

func Update() {
  uiInstance.base.update()
}

func Draw(surface *sdl.Surface) {
  uiInstance.base.draw(surface)
}

func DoInput(e *sdl.Event) bool {
  switch e.Type {
    // Mouse input:  
    case sdl.MOUSEBUTTONDOWN:
      log.Stderr("Mouse button down")
      x := int(e.MouseButton().X)
      y := int(e.MouseButton().Y)
      
      widget := uiInstance.base.getWidgetAt(x, y)
      if widget != nil {
        log.Stderr("Found widget", widget)
        uiInstance.active = widget
        fmt.Printf("Active is now: %p\n", uiInstance.active)
        widget.pointerPressed(x, y)
      }
      break
    case sdl.MOUSEBUTTONUP:
      log.Stderr("Mouse button up")
      x := int(e.MouseButton().X)
      y := int(e.MouseButton().Y)
      
      //widget := uiInstance.base.getWidgetAt(x, y)
      GetActiveWindow().pointerReleased(x, y)
      
      break
    
    // Keyboard input:
    case sdl.KEYDOWN:
      log.Stderrf("KEYDOWN - scan: %d, sym: %d, mod: %d, unicode: %d, pad0: %d, pad1: %d", e.Keyboard().Keysym.Scancode, e.Keyboard().Keysym.Sym, e.Keyboard().Keysym.Mod, e.Keyboard().Keysym.Unicode, e.Keyboard().Keysym.Pad0, e.Keyboard().Keysym.Pad1)
      uiInstance.active.keyPressed(int(e.Keyboard().Keysym.Unicode))
      break
    case sdl.KEYUP:
      log.Stderrf("KEYUP - scan: %d, sym: %d, mod: %d, unicode: %d, pad0: %d, pad1: %d", e.Keyboard().Keysym.Scancode, e.Keyboard().Keysym.Sym, e.Keyboard().Keysym.Mod, e.Keyboard().Keysym.Unicode, e.Keyboard().Keysym.Pad0, e.Keyboard().Keysym.Pad1)
      log.Stderr(uiInstance.active)
      uiInstance.active.keyReleased(int(e.Keyboard().Keysym.Unicode))
      break
    default:
      return false;
  }
  return true;
}

